package com.xinan.utils;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Properties;


import com.jfinal.kit.StringKit;
import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SearchSql;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class FileAddController extends Controller {


    private static String filePath = "";
    private static String docTypes = "";
    private static String filesavetype = "FLIE";
    static {

        Properties r = PropertiesHelper.loadProperty("/upload.properties");
        if (!r.isEmpty()) {
            try {
                filePath = r.getProperty("filePath");
                docTypes = r.getProperty("DOC_EDIT_TYPE");
                filesavetype = r.getProperty("filesavetype");
            } catch (Exception e) {
                Logger.getLogger(Upload.class).error("无法读filePath参数", e);
            }
        }
    }
    public void index() {
        render("/WEB-INF/views/archives/oaArchives.html");
    }



    @Before(SearchSql.class)
    public void queryFile() {
        String   archivesfileid=getPara("fileid");
        List<Record> file = Db.find("select  path,type,size,filename,id from  oa_archivesfile  where    archivesfileid=  '"+archivesfileid+"'");
        setAttr("filelist",file);
        render("/WEB-INF/views/js/ddxx/file.html");
    }

    public void edit() {
        String   archivesfileid=getPara("fileid");
        List<Record> file = Db.find("select  path,type,size,filename,id from  oa_archivesfile  where    archivesfileid=  '"+archivesfileid+"'");
        setAttr("filelist",file);
        setAttr("path",filePath);
        render( "archives/file.html");
    }

    public void fileview() {
        String   archivesfileid=getPara("fileid");
        List<Record> file = Db.find("select  path,type,size,filename,id from  oa_archivesfile  where    archivesfileid=  '"+archivesfileid+"'");
        setAttr("filelist",file);
        setAttr("path",filePath);
        render( "archives/fileview.html");
    }

    //文件查阅
    public void  view(){
        String file=  getPara("file");
        String path= filePath +File.separator+File.separator       +file;
        setAttr("path",path);
        String   type=getPara("type");
        String   print=getPara("print");
        setAttr("print",print);   // 是否打印标记

        if(type.equals("pdf")){
            renderJsp("archives/editpdf.jsp");
        }      else if(type.equals("xls") || type.equals("xlsx")) {
            renderJsp("archives/editexcl.jsp");
        }     else {
            renderJsp("archives/editword.jsp");
        }
    }

    public void tree(){
        List<Record> org_tree = Db.find(" select id , name as text ,pid, from auth_org");
        renderJson(org_tree);
    }

    /**
     * @param
     * @return string
     */
    public  void  addFile()  {

        Upload upload = new Upload();

        String fjid = Identities.uuid2();// 唯一 32位编码
        upload.setFileName(fjid);
        int uptype = Upload.FILE;
        Map map = upload.upload(getRequest() , 0, uptype); //文件删除
        if (map.isEmpty()) {
            setAttr("success", false);
            setAttr("msg", "未知");
            renderJson();
        } else if (map.containsKey("error")) {
            setAttr("success", false);
            setAttr("msg", ""+ map.get("error") +"");
            renderJson();
        }
        String ext = getFileExt((String) map.get("FILE_NAME"));


        String wjmc= map.get("FILE_NAME").toString();
        String path=map.get("FILE_PATH").toString();
        String archivesfileid= getPara(0);
        String size=map.get("FILE_SIZE").toString();
        String type= ext;
        try {
            //文件表插入
            Record user = new Record().set("PATH", path).set("size",size).set("filename", wjmc).set("archivesfileid",archivesfileid).set("type",type);
            Db.save("oa_archivesfile", user);
            user.get("id");
            setAttr("success", true);
            setAttr("msg", "成功");
            setAttr("fjid",user.get("id"));
            setAttr("fjmc",wjmc);
            setAttr("path",path);
            setAttr("wjlx",type);

            renderJson();
        } catch(Exception e){
            setAttr("success", false);
            setAttr("msg", "数据保存失败请联系管理员");
            renderJson();
        }
    }



    /**
     * 根据文件名获取文件对应的文件类型
     *
     * @param
     * @return string
     */
    public String getFileExt(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            String ext = "";
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length() - 1))) {
                ext = filename.substring(i + 1);
            }
            return ext;
        } else {
            return "0";
        }
    }
    public boolean delete(String archivesfileid) {
        boolean succeed = false;
            String id=getPara("id");
            List<Record> list=Db.find("select * from  oa_archivesfile where archivesfileid =  '"+getPara("archivesfileid")+"'");
            if(list.size()>0){
                 	succeed	=	Db.deleteById("oa_archivesfile","archivesfileid",getPara("archivesfileid"));//文件表删除
                for (int i=0;i<list.size();i++){
                    String path = (String)list.get(i).get("path");
                    path=filePath+File.separator+File.separator +path;
                    String del=  delFiles(path);
                }
            }
           return  succeed;
    }

    public void delFile() {
        String id=getPara("ID");
        Record user = new Record().set("ID", id);
        List<Record> wjList =Db.find("	SELECT  *  from oa_archivesfile where ID="+id+"");
        if (wjList.size()>0) {
            for(int i=0; i<wjList.size(); i++) {
                String path =   (String)wjList.get(i).get("path");
                path=filePath+File.separator+ File.separator+path;
                String del= delFiles(path);
            }
        }
        boolean i = Db.deleteById("oa_archivesfile","ID",id);
        if (i == true) {
            setAttr("success", true);
            setAttr("msg", "删除附件成功");
            setAttr("fjid",id);
            renderJson();

        } else {
            setAttr("success", false);
            setAttr("msg", "删除附件失败");
            setAttr("fjid",id);
            renderJson();

        }
    }

    /**
     * 文件删除.
     */
    private String delFiles(String file) {
        File f = new File(file);
        // 路径为文件且不为空则进行删除

        if (f.isFile() && f.exists()) {
            f.delete();
            //
            return "1";
        } else {
            return "0";
        }
    }




}

